<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Models\Role;
use App\Http\Controllers\Controller;

class CharacterController extends Controller
{

    /**
     * 获取角色列表
     */
    public function list(Request $request)
    {
        $page = (int)$request->query('page', 1);
        $limit = (int)$request->query('limit', 20);

        $query = Role::query();

        $total = $query->count();

        if (is_null($total)) {
            abort(404);
        }

        $maxPage = ceil($total / $limit);

        if ($page > $maxPage) {
            abort(404);
        }

        $roles = $query->forPage($page, $limit)
                       ->get();

        if (is_null($roles)) {
            abort(404);
        }

        return [
            'data' => $roles,
            'pagination' => [
                'page' => $page,
                'limit' => $limit,
                'total_page' => $maxPage,
                'total' => $total,
            ],
        ];
    }

    /**
     * 新增编辑角色
     */
    public function create(Request $request)
    {
        $body = $request->post();

        $id = $request->query('id', 0);

        $role = Role::query()
                    ->findOrNew($id);

        $role->name = trim($body['role']);
        $role->role_type = $body['role_type'];
        $role->status = $body['status'];
        $role->camp = $body['camp'];

        $role->save();

        return $role;
    }

    /**
     * 删除角色
     */
    public function delete(int $id)
    {
        $role = Role::query()
                    ->find($id);

        if (is_null($role)) {
            abort(404);
        }

        $role->delete();

        return $role;
    }

    /**
     * 对局中使用角色
     */
    public function playing()
    {
        return Role::query()
                   ->where('status', 1)
                   ->get();
    }
}
